<?php
namespace app\restaurant\controller;

use app\ApiRest;

use app\restaurant\model\ClassConnect;
use app\restaurant\model\ClassDate;
use app\restaurant\model\Config;
use app\restaurant\model\OrderGoods;
use app\restaurant\model\Progress;
use app\restaurant\model\RefundOrder;
use app\restaurant\model\ResClass;
use app\restaurant\model\StoreStaff;
use app\restaurant\model\Table;
use app\restaurant\model\TransporterOrder;
use app\restaurant\server\Context;
use app\restaurant\server\DadaApi;
use think\App;

use app\restaurant\model\Car as model;

use app\restaurant\model\Printer;

use app\restaurant\model\Goods;

use app\restaurant\model\FeedingCar;

use app\restaurant\model\Order;

use app\restaurant\model\Store;


use think\facade\Db;


class IndexSetting extends ApiRest
{

    protected $model;

    protected $staff_model;

    protected $printer_model;

    protected $goods_model;

    protected $feeding_car_model;

    protected $store_info;

    protected $order_model;

    protected $store_model;

    protected $refund_model;


    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new Model();

        $this->staff_model = new StoreStaff();

        $this->printer_model = new Printer();

        $this->goods_model = new Goods();

        $this->order_model = new Order();

        $this->refund_model = new RefundOrder();

        $this->feeding_car_model = new FeedingCar();

        $this->store_model = new Store();

        $store = $this->staff_model->getStaffStore($this->getUserId(),1);

        if(empty($store)){

            $this->errorMsg('你不是门店管理员');

        }

        $dis[] = ['id','=',$store['store_id']];

        $dis[] = ['status','>',-1];

        $store = $this->store_model->storeInfo($dis);

        if(empty($store)){

            $this->errorMsg('门店已经关闭');
        }

        $this->store_info = $store;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-16 11:24
     * @功能说明:打印机列表
     */
    public function printerList(){

        $dis[] = ['store_id','=',$this->store_info['id']];

        $dis[] = ['status','>',-1];

        $dis[] = ['uniacid','=',$this->_uniacid];

        $data = $this->printer_model->dataList($dis,10);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-20 11:09
     * @功能说明:添加打印机
     */
    public function printerAdd(){

        $input = $this->_input;

        $input['store_id'] = $this->store_info['id'];

        $input['uniacid']  = $this->_uniacid;

        $res = $this->printer_model->dataAdd($input);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-20 11:31
     * @功能说明:编辑打印机
     */
    public function printerUpdate(){

        $input = $this->_input;

        $res = $this->printer_model->dataUpdate(['id'=>$input['id']],$input);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-24 18:29
     * @功能说明:员工端门店详情
     */
    public function staffStoreInfo(){

        $goods_model = new Goods();

        $list = $this->order_model->storeOrderFrom($this->store_info['id'],'',$this->_uniacid);
        //订单实际金额
        $data['true_price']  = $list['true_price'];
        //订单总量
        $data['order_count'] = $list['order_count'];
        //商品总量
        $data['goods_num']   = $goods_model->where(['store_id'=>$this->store_info['id']])->where('status','>',-1)->count();
        //门店详情
        $data['store_info']  = $this->store_info;

        return $this->success($data);


    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 13:29
     * @功能说明:编辑
     */
    public function goodsUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $input['uniacid'] = $this->_uniacid;

        $data = $this->goods_model->goodsUpdate($dis,$input);

        return $this->success($data);

    }




    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:35
     * @功能说明:员工端订单列表
     */
    public function staffOrderList(){

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.staff_id','=',$this->getUserId()];

        $dis[] = ['a.transaction_id','<>',0];
        //状态
        if(!empty($input['pay_type'])){

            $dis[] = ['a.pay_type','>',0];
            //商家待接单
            if($input['pay_type']==1){

                $dis[] = ['g.status','=',0];

            //骑手待接单
            }elseif ($input['pay_type']==2){

                $dis[] = ['g.status','=',1];

            //配送中
            } elseif($input['pay_type']==3){

                $dis[] = ['g.status','in',[2,3,100]];

            }else{
                //
                $dis[] = ['g.status','=',$input['pay_type']];
                //订单异常
                if($input['pay_type']==5){
                    //只有三方平台的问题才叫异常
                    $dis[] = ['g.cancel_from','in',[1,3,4]];

                }

            }

        }
        if(isset($input['order_type'])){

            $dis[] = ['a.order_type','=',$input['order_type']];

        }
        $where = [];
        //商品
        if(!empty($input['goods_name'])){

            $where[] = ['f.goods_name','like','%'.$input['goods_name'].'%'];

            $where[] = ['a.order_code','like','%'.$input['goods_name'].'%'];
        }

        $data = $this->order_model->staffOrderList($dis,$where);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-24 18:52
     * @功能说明:营业数据
     */
    public function listFrom(){

        $toDay = date('Y-m-d',time());

        $yesterday = date('Y-m-d',time()-86400);
        //昨日
        $data['yesterday'] = $this->order_model->storeOrderFrom($this->store_info['id'],$yesterday,$this->_uniacid);
        //今日
        $data['to_day']    = $this->order_model->storeOrderFrom($this->store_info['id'],$toDay,$this->_uniacid);
        //所有
        $data['all']       = $this->order_model->storeOrderFrom($this->store_info['id'],'',$this->_uniacid);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-24 18:58
     * @功能说明:商品排行
     */
    public function goodsTop(){

        $input = $this->_input;

        $start_time = !empty($input['start_time'])?$input['start_time']:0;

        $end_time   = !empty($input['end_time'])?$input['end_time']:0;

        $data  = $this->goods_model->goodsTop($this->store_info['id'],$input['sort'],$start_time,$end_time);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-26 10:01
     * @功能说明:门店修改
     */
    public function storeUpdate(){

        $input  = $this->_input;

        $res = $this->store_model->where(['id'=>$this->store_info['id']])->update($input);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-20 09:48
     * @功能说明:员工端商品列表
     */
    public function staffGoodsList(){

        $input = $this->_param;


        $dis[] = ['a.status','>',-1];

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        if(!empty($input['cate_id'])){

            $dis[] = ['a.cate_id','=',$input['cate_id']];
        }

        $dis[] = ['a.store_id','=',$this->store_info['id']];

        if(!empty($input['title'])){

            $dis[] = ['a.title','like','%'.$input['title'].'%'];

        }

        $data  = $this->goods_model->getStaffGoodsList($dis,$input['sort']);

        return $this->success($data);


    }

    /**
     * @author chenniang
     * @DataTime: 2020-10-26 17:25
     * @功能说明:自提商品核销
     */
    public function selfOrderHx(){

        $input = $this->_input;

        $order = $this->order_model->orderInfo(['id'=>$input['id']]);

        if(empty($order)){

            $this->errorMsg('订单不存在');
        }
        //0是外卖 1是堂食 2是自提
        if($order['order_type']!=2){

            $this->errorMsg('只有自提订单才能核销');

        }

        if($order['pay_type']!=1){

            $this->errorMsg('订单状态错误');

        }

        $config_model = new Config();

        $config = $config_model->configInfo(['uniacid'=>$order['uniacid']]);

        if($config['hx_pass']!=$input['hx_pass']){

            $this->errorMsg('密码错误');
        }

        $transporter_model = new TransporterOrder();

        $transporter_model->where(['order_id'=>$input['id']])->update(['status'=>4]);

        $progress_model = new Progress();
        //添加用户收货成功进度
        $progress_model->userGetGoods($order['uniacid'],$order['order_code']);
        //修改订单状态
        $this->order_model->endOrder($input['id'],$this->getUserId());

        return $this->success(true);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-03 09:27
     * @功能说明:获取物流类
     */
    public function getClass(){

        $calss  = new DadaApi();

        return $calss;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-30 10:28
     * @功能说明:商家接单(发单)
     */
    public function acceptOrder(){

        $input = $this->_input;

        $context = new Context($input['id']);

        Db::startTrans();

        $res = $context->addOrder($input['id']);

        if(!empty($res['code'])&&$res['code']==500){

            $this->errorMsg($res['msg']);
        }

        if(isset($res['code'])&&$res['code']!=0){

            $this->errorMsg($res['msg']);

        }

        Db::commit();

        return $this->success($res['code']);

    }




    /**
     * @author chenniang
     * @DataTime: 2020-11-03 09:26
     * @功能说明:商家重新发单
     */
    public function reAcceptOrder(){

        $input = $this->_input;

        $context = new Context($input['id']);

        Db::startTrans();

        $res = $context->reAddOrder($input['id']);

        if(!empty($res['code'])&&$res['code']==500){

            $this->errorMsg($res['msg']);
        }

        if(isset($res['code'])&&$res['code']!=0){

            $this->errorMsg($res['msg']);

        }

        Db::commit();

        return $this->success($res['code']);


    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-04 14:48
     * @功能说明:商家统一退款
     */
    public function agreeRefund(){

        $input = $this->_input;

        $refund_order = new RefundOrder();

        $res = $refund_order->agreeRefund($input['id'],$input['price'],$this->payConfig($this->_uniacid));

        return $this->success($res);


    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-04 14:48
     * @功能说明:商家统一退款
     */
    public function noAgreeRefund(){

        $input = $this->_input;

        $refund_order = new RefundOrder();

        $res = $refund_order->noAgreeRefund($input['id']);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-04 16:54
     * @功能说明:商家取消三方平台的订单
     */
    public function cancelSendOrder(){

        $input = $this->_input;

        $context = new Context($input['order_code']);

        $res = $context->orderCancel($input['order_code']);

        if(isset($res['code'])&&$res['code']!=0){

            $this->errorMsg($res['msg']);
        }

        return $this->success($res);


    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-05 09:29
     * @功能说明:商家端退款订单
     */
    public function refundOrderList(){
        //审核过期售后订单
        $this->refund_model->checkOrder($this->_uniacid,$this->payConfig($this->_uniacid));

        $input = $this->_input;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.user_cancel','=',0];

        $dis[] = ['a.store_id','=',$this->store_info['id']];

        if(!empty($input['status'])){

            $dis[] = ['a.status','=',$input['status']];
        }

        if(isset($input['order_type'])){

            $dis[] = ['b.order_type','=',$input['order_type']];
        }

        $where = [];

        if(!empty($input['name'])){

            $where[] = ['c.goods_name','like','%'.$input['name'].'%'];

            $where[] = ['b.order_code','like','%'.$input['name'].'%'];

            $where[] = ['a.order_code','like','%'.$input['name'].'%'];
        }

        $data = $this->refund_model->refundOrderList($dis,$where);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-06 14:04
     * @功能说明:商家备货成功
     */
    public function StoreStockUp(){

        $input = $this->_input;

        $order = $this->order_model->orderInfo(['id'=>$input['id']]);

        $transporter_model = new TransporterOrder();

        $progress_model    = new Progress();

        $transporter_model->where(['order_id'=>$input['id']])->update(['status'=>2]);

        $res = $progress_model->storeStockUp($order['uniacid'],$order['order_code']);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-10 15:14
     * @功能说明:商家配送的时候 商家作为骑手接单
     */
    public function riderAcceptOrder(){

        $input = $this->_input;

        $order = $this->order_model->orderInfo(['id'=>$input['id']]);

        $transporter_model = new TransporterOrder();

        $progress_model    = new Progress();

        $transporter_model->where(['order_id'=>$input['id']])->update(['status'=>2,'transporter_name'=>$this->store_info['title'],'transporter_phone'=>$this->store_info['mobile']]);

        $res = $progress_model->riderAcceptOrder($order['uniacid'],$order['order_code']);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-10 15:14
     * @功能说明:商家配送的时候 商家作为骑手接货
     */
    public function riderGoodsUp(){

        $input = $this->_input;

        $order = $this->order_model->orderInfo(['id'=>$input['id']]);

        $transporter_model = new TransporterOrder();

        $progress_model    = new Progress();

        $transporter_model->where(['order_id'=>$input['id']])->update(['status'=>3,'transporter_name'=>$this->store_info['title'],'transporter_phone'=>$this->store_info['mobile']]);
        //骑手接单
        $res = $progress_model->riderAcceptOrder($order['uniacid'],$order['order_code']);
        //骑手取货
        $res = $progress_model->riderGoodsUp($order['uniacid'],$order['order_code']);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-10 15:14
     * @功能说明:商家配送的时候 商家作为骑手送货到达
     *
     */
    public function riderGoodsSuccess(){

        $input = $this->_input;

        $order = $this->order_model->orderInfo(['id'=>$input['id']]);

        $transporter_model = new TransporterOrder();

        $progress_model    = new Progress();

        $transporter_model->where(['order_id'=>$input['id']])->update(['status'=>4,'finish_time'=>time(),'transporter_name'=>$this->store_info['title'],'transporter_phone'=>$this->store_info['mobile']]);
        //商品送达
        $res = $progress_model->riderGoodsSuccess($order['uniacid'],$order['order_code']);

        return $this->success($res);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-02-27 15:03
     * @功能说明:商家添加排班
     */
    public function addClassData(){

        $input = $this->_input;

        $date_model    = new ClassDate();

        $connect_model = new ClassConnect();

        $class_model   = new ResClass();

        $class = $class_model->dataInfo(['id'=>$input['class_id']]);

        if(empty($class)){

            $this->errorMsg('班次不存在');

        }
        //确保是0点
        $input['time'] = strtotime(date('Y-m-d',$input['time']));

        Db::startTrans();
        //修改班次相关信息
       // $class_model->updateConnect(['id'=>$input['class_id']],['start_time'=>$input['start_time'],'end_time'=>$input['end_time']]);
        //清空该店该日所有的数据
        $res = $date_model->delDateClass($this->store_info['id'],$input['time'],$input['class_id']);

        foreach ($input['bind'] as $value){

            if(empty($value['staff_id'])){

                continue;
            }
            //清空该员工当天的数据
            $date_model->where(['staff_id'=>$value['staff_id'],'date'=>$input['time']])->where('class_id','<>',$input['class_id'])->delete();

            $dis = [

                'uniacid' => $this->_uniacid,

                'store_id'=> $this->store_info['id'],

                'staff_id'=> $value['staff_id'],

                'class_id'=> $class['id'],

                'date'    => $input['time']
            ];
            //添加班次
            $have = $date_model->dataInfo($dis);

            if(empty($have)){

                $time_str = $date_model->changeTime($input['time'],$class['start_time'],$class['end_time']);

                $dis['start_time']  = $time_str['start_time'];

                $dis['end_time']    = $time_str['end_time'];

                $dis['class_title'] = $class['title'];

                $res = $date_model->dataAdd($dis);

                $id = $date_model->getLastInsID();

                if($res!=1){

                    Db::rollback();

                    $this->errorMsg('添加失败1');

                }

            }else{

                $id = $have['id'];
            }
            //绑定桌号
            $insert = [

                'uniacid' => $this->_uniacid,

                'date_id' => $id,

                'table_id'=> $value['table_id']

            ];

            $res = $connect_model->dataAdd($insert);

            if($res!=1){

                Db::rollback();

                $this->errorMsg('添加失败');

            }
        }

        Db::commit();

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-02 11:42
     * @功能说明:获取该天有哪些班次
     */
    public function dateClass(){

        $input = $this->_param;

        $date_model = new ClassDate();

        $dis = [

            'date'     => $input['time'],

            'store_id' => $this->store_info['id']
        ];

        $data = $date_model->where($dis)->field('class_id,class_title')->group('class_id')->select()->toArray();

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-02 11:41
     * @功能说明:管理段端员工排班管理
     */
    public function classDataList(){

        $input = $this->_param;

        $dis = [

            'c.store_id' => $this->store_info['id'],

            'c.date'     => $input['time'],

            'c.class_id' => $input['class_id']
        ];

        $date_model = new ClassDate();

        $data = $date_model->tableStaffList($dis);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-01 10:41
     * @功能说明:班次下拉
     */
    public function classSelect(){

        $input = $this->_param;

        $dis[] = ['uniacid','=',$this->_uniacid];

        $dis[] = ['status','>',-1];

        $dis[] = ['store_id','=',$this->store_info['id']];

        $date_model = new ResClass();

        $data = $date_model->where($dis)->select()->toArray();

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-22 10:30
     * @功能说明:增加桌号
     */
    public function tableAdd(){

        $input = $this->_input;

        $input['uniacid'] = $this->_uniacid;

        $input['store_id'] = $this->store_info['id'];

        $table_model = new Table();

        $res = $table_model->dataAdd($input);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-01 18:11
     * @功能说明:修改桌号码
     */
    public function tableQr(){

        $input  = $this->_input;

        $tab_id = $input['table_id'];

        $table_model = new Table();

        $input['key']= 41;

        $input['type']= 23;

        $data  = longbingCreateWxCode($this->_uniacid,$input,'pages/user/home');

        $qr    = '';

        if(isset($data['qr_path'])){

            $data = transImagesOne($data ,['qr_path'] ,$this->_uniacid);

            $res  = $table_model->dataUpdate(['id'=>$tab_id],['qr'=>$data['qr_path']]);

            $qr   = $data['qr_path'];

        }

        return $this->success($qr);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-22 10:31
     * @功能说明:桌号列表
     */
    public function tableList(){

        $input = $this->_input;

        $dis[] = ['store_id','=',$this->store_info['id']];

        $dis[] = ['status','>',-1];

        if(!empty($input['title'])){

            $dis[] = ['like','%'.$input['title'].'%'];

        }

        $table_model = new Table();

        $data = $table_model->dataList($dis,10);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-22 10:33
     * @功能说明:桌号详情
     */
    public function tableInfo(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $table_model = new Table();

        $data = $table_model->dataInfo($dis);

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-22 10:35
     * @功能说明:桌号编辑
     */
    public function tableUpdate(){

        $input = $this->_input;

        $dis = [

            'id' => $input['id']
        ];

        $table_model = new Table();

        $data = $table_model->dataUpdate($dis,$input);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-02 14:25
     * @功能说明:排班员工下拉
     */
    public function staffSelect(){

        $input = $this->_param;

        $date_model = new ClassDate();

//        $where = [
//
//            'store_id' => $this->store_info['id'],
//
//            'date'     => $input['time'],
//
//        ];
//
//        $staff_id   = $date_model->where($where)->where('class_id','<>',$input['class_id'])->column('staff_id');

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.store_id','=',$this->store_info['id']];

//        $dis[] = ['b.fans_id','not in',$staff_id];
        //获取员工
        $data = $this->staff_model->staffSelect($dis);

        if(!empty($data)){

            foreach ($data as &$v){

                $v['staff_name'] = !empty($v['staff_name'])?$v['staff_name']:lbUserName($v['staff_id']);
            }
        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-02 14:09
     * @功能说明:班次桌号下拉
     */
    public function dateTableSelect(){

        $input = $this->_param;

        $dis = [

            'store_id' => $this->store_info['id'],

            'status'   => 1
        ];

        $table_model = new Table();

        $date_model  = new ClassDate();

        $data = $table_model->where($dis)->select()->toArray();

        if(!empty($data)&&!empty($input['time'])){

            foreach ($data as &$v){

                $dis = [

                    'a.store_id' => $this->store_info['id'],

                    'b.table_id' => $v['id'],

                    'a.date'     => $input['time'],

                    'a.class_id' => $input['class_id'],
                ];

                $staff = $date_model->bindTableStaff($dis);

                $v['staff_id']   = !empty($staff)?$staff['staff_id']:0;

                $v['staff_name'] = !empty($staff)?lbUserName($staff['staff_id']):'';


            }

        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-26 09:29
     * @功能说明:班次列表
     */
    public function classList(){

        $input = $this->_input;

        $dis = [

            'uniacid' => $this->_uniacid,

            'store_id'=> $this->store_info['id']
        ];

        $class_model = new ResClass();

        $class_model->initreset($dis);

        $res = $class_model->dataList($dis,10);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-26 09:29
     * @功能说明:添加班次
     */
    public function classAdd(){

        $input = $this->_input;

        $input['uniacid']  = $this->_uniacid;

        $input['store_id'] = $this->store_info['id'];

        $class_model = new ResClass();

        $check = $class_model->checkClass($input);

        if(!empty($check['code'])){

            $this->errorMsg($check['msg']);
        }

        $res = $class_model->dataAdd($input);

        return $this->success($res);

    }

    /**
     * @author chenniang
     * @DataTime: 2021-02-22 10:58
     * @功能说明:排班详情
     */
    public function classInfo(){

        $input = $this->_input;

        $dis = [

            'uniacid' => $this->_uniacid,

            'store_id'=> $input['store_id']
        ];

        $class_model = new ResClass();

        $res = $class_model->dataInfo($dis);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-22 11:01
     * @功能说明:编辑排班
     */
    public function classUpdate(){

        $input = $this->_input;

        $class_model = new ResClass();

        $input['uniacid'] = $this->_uniacid;

        $input['store_id']= $this->store_info['id'];

        $check = $class_model->checkClass($input);

        if(!empty($check['code'])){

            $this->errorMsg($check['msg']);
        }

        $dis = [

            'id'=> $input['id']
        ];

        $class = $class_model->dataInfo($dis);

        $dis['store_id'] = $class['store_id'];

        $res = $class_model->updateConnect($dis,$input);

        return $this->success($res);
    }





}
